package com.zy.common.tree;

import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import sun.reflect.generics.tree.Tree;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;


@Data
@AllArgsConstructor
@NoArgsConstructor
public class TreeNode implements Serializable {

    private Integer id;
    private Integer pid;
    private String title;
    private String icon;
    private String href;
    private String target;
    private Boolean spread;
    @JsonInclude(value = JsonInclude.Include.NON_EMPTY)
    private List<TreeNode> child=new ArrayList<>();

    /**
     * 登陆成功之后系统主而需要的菜单树的json对象构造器
     * @param id
     * @param pid
     * @param title
     * @param icon
     * @param href
     * @param target
     * @param spread
     */
    public TreeNode(Integer id, Integer pid, String title, String icon, String href, String target, Boolean spread) {
        this.id = id;
        this.pid = pid;
        this.title = title;
        this.icon = icon;
        this.href = href;
        this.target = target;
        this.spread = spread;
    }




    public  static class TreeNodeBuilder{
        /**
         *
         * @param treeNodes 要生成有层级关系的源数据
         * @param topId  最顶层的pid 根节点的pid
         * @return
         */
        public static List<TreeNode> build(List<TreeNode> treeNodes,Integer topId){

            List<TreeNode> nodes=new ArrayList<>();

            for (TreeNode n1 : treeNodes) {
                if(n1.getPid().equals(topId)){
                    //说明n1节点是
                    nodes.add(n1);
                }
                for (TreeNode n2 : treeNodes) {
                    if(n2.getPid().equals(n1.getId())){
                        //说明n2是n1的子节点 应该放到n1的clild里面
                        n1.getChild().add(n2);
                    }
                }
            }
            return nodes;
        }
    }
}
